package se.webbzon.boltzmann.font;

import java.awt.Font;
import java.awt.FontFormatException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayDeque;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import se.webbzon.boltzmann.loader.Loader;
import se.webbzon.boltzmann.loader.LoaderException;
import se.webbzon.boltzmann.loader.LoaderUtilityPointer;

public class FontLoaderMap implements Loader {

	// A collection of resource names related to this loader
	private final static Collection<String> resourceNames = new ArrayDeque<String>();

	static {
		resourceNames.add("font");
	}

	// A map containing all loaded fonts
	private final Map<String,Font> content;

	/*============================================================
	Constructors
	============================================================*/

	public FontLoaderMap() {
		content = new HashMap<String,Font>();
	}

	/*============================================================
	Public Methods
	============================================================*/

	@Override public String getCategory() {
		return "fonts";
	}

	@Override public Collection<String> getSupportedResources() {
		return resourceNames;
	}

	@Override public void load(	LoaderUtilityPointer pointer, String resourceName,
			Map<String, String> attributeMap) throws LoaderException {
		String name = attributeMap.get("name");
		String filename = attributeMap.get("file");

		try {
			URL url = new URL(pointer.getXMLURL(),filename);
			InputStream is = url.openStream();
			content.put(name, Font.createFont(Font.TRUETYPE_FONT, is));
			is.close();
		} catch (IOException | FontFormatException e) {
			throw new LoaderException(e);
		}
		
	}

	/** Returns the font map associated with this instance. **/
	public Map<String,Font> getMap() {
		return Collections.unmodifiableMap(content);
	}

}
